package org.zkdemo.zkapi;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

import org.zkdemo.api.capabilities.Capabilities;

public class ConfigUtils {

	public static final String MODULES = "modules";
	public static final String DISCOVERY = "discovery";

	public static final byte[] serializeCapabilities(Collection<Capabilities> capabilities) {
		StringBuilder ret = new StringBuilder("[");
		Iterator<Capabilities> it = capabilities.iterator();
		while (it.hasNext()) {
			ret.append(it.next());
			if (it.hasNext()) {
				ret.append(",");
			}
		}
		ret.append("]");

		try {
			return ret.toString().getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Error encoding bytes.", e);
		}
	}

	public static final Collection<Capabilities> deserializeCapabilities(String capabilitiesString) {
		if ("".equals(capabilitiesString)) {
			return Collections.emptyList();
		}

		Collection<Capabilities> capabilities = new ArrayList<Capabilities>();

		String[] splits = capabilitiesString.split(",");
		for (String split : splits) {
			split = split.trim();
			if (!"".equals(split)) {
				capabilities.add(Capabilities.valueOf(split));
			}
		}

		return capabilities;
	}

	public static final Collection<Capabilities> deserializeCapabilitiesEncapsulated(String capabilitiesString) {
		if ("".equals(capabilitiesString)) {
			return deserializeCapabilities(capabilitiesString);
		}

		capabilitiesString = capabilitiesString.substring(1, capabilitiesString.length() - 1);

		return deserializeCapabilities(capabilitiesString);
	}
}
